package mobi.yuanshen.controller;

import cn.dev33.satoken.annotation.SaCheckPermission;
import cn.hutool.core.util.StrUtil;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.tags.Tag;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import mobi.yuanshen.common.Exception.ParamException;
import mobi.yuanshen.common.constants.PermissionCodeConstants;
import mobi.yuanshen.domain.dto.AddAdminDTO;
import mobi.yuanshen.domain.dto.UserLoginDTO;
import mobi.yuanshen.service.AdminService;
import mobi.yuanshen.common.utils.Result;
import org.springframework.web.bind.annotation.*;

@RestController
@RequestMapping("/admin")
@Tag(name = "用户模块")
@RequiredArgsConstructor
@Slf4j
public class AdminController {

    private final AdminService adminService;

    @PostMapping("/login")
    @Operation(summary = "登录")
    public Result<String> login(@RequestBody UserLoginDTO userLoginDTO) {
        log.info("用户登录：{}", userLoginDTO);
        if (StrUtil.isBlank(userLoginDTO.getUsername())
                || StrUtil.isBlank(userLoginDTO.getPassword())
                || StrUtil.isBlank(userLoginDTO.getPicCode())
                || StrUtil.isBlank(userLoginDTO.getPicCodeKey())
        ) {
            throw new ParamException();
        }
        String token = adminService.login(userLoginDTO);
        return Result.success(token);
    }

    @PostMapping("/register")
    @Operation(summary = "注册管理员")
    public Result addAdmin (@RequestBody AddAdminDTO addAdminDTO) {
        log.info("添加管理员：{}", addAdminDTO);
        if (StrUtil.isBlank(addAdminDTO.getAdminName())
                || StrUtil.isBlank(addAdminDTO.getUsername())
                || StrUtil.isBlank(addAdminDTO.getPassword())
                || StrUtil.isBlank(addAdminDTO.getPhone())
        ) {
            throw new ParamException();
        }
        adminService.addAdmin(addAdminDTO);
        return Result.operationSuccess();
    }

    @GetMapping("/findUsers")
    @Operation(summary = "查询用户列表")
    @SaCheckPermission(PermissionCodeConstants.SYSTEM_MANAGE)
    public Result findUsers() {
        return Result.success(adminService.list());
    }

}
